﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="返料规则编码" prop="RuleCode">
            <a-input disabled v-model="entity.RuleCode" autocomplete="off" placeholder="系统自动生成"/>
            <!-- <Myuser v-model="entity.Object" /> -->
            <!-- <Myuser v-if="this.a == 2" v-model="entity.CustomerName" /> -->

            <!-- <Myuser v-if="this.titie == '编辑样品申请表信息'" v-model="entity.Object" /> -->
          </a-form-model-item>
        </a-col>

        <a-col :span="8">
          <a-form-model-item label="返料规则名称" prop="RuleName">
            <a-input v-model="entity.RuleName" autocomplete="off"/>
            <!-- <Myuser v-model="entity.Object" /> -->
            <!-- <Myuser v-if="this.a == 2" v-model="entity.CustomerName" /> -->

            <!-- <Myuser v-if="this.titie == '编辑样品申请表信息'" v-model="entity.Object" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="返料类型" prop="GiftType">
            <a-select v-model="entity.GiftType" style="width: 100%" placeholder="返料类型" @change="GiftTypeChange">
              <a-select-option v-for="item in MaterialReturn" :key="item.Id" :value="item.DicName">
                {{ item.DicName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="开始效期" prop="StartDate">
            <a-date-picker format="YYYY-MM-DD" style="width: 100%" v-model="entity.StartDate"/>
            <!-- <a-input v-model="entity.StartDate" autocomplete="off" placeholder="开始效期" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="结束效期" prop="EndDate">
            <a-date-picker
              format="YYYY-MM-DD"
              style="width: 100%"
              v-model="entity.EndDate"
              :disabledDate="disabledDate"
            />
            <!-- <a-input v-model="entity.EndDate" autocomplete="off" placeholder="结束效期" /> -->
          </a-form-model-item>
        </a-col>
        <!-- <a-col :span="8">
          <a-form-model-item label="返料发货基础" prop="GiftDeliveryBasics">
            <a-input v-model="entity.GiftDeliveryBasics" autocomplete="off" placeholder="返料发货基础" />
          </a-form-model-item>
        </a-col> -->

        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remark">
            <a-textarea v-model="entity.Remark" autocomplete="off"/>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <MaterialChoose ref="materialChoose" @onChoose="handleChoose"></MaterialChoose>
    <ReturnMaterialChoose ref="ReturnMaterialChoose" @handlerClose="TableClose"></ReturnMaterialChoose>

    <a-table
      ref="table"
      :scroll="{ y: 530 }"
      :columns="entity.GiftType === '销售返利' ? columns2 : columns"
      :rowKey="(row, index) => index"
      :dataSource="data"
      :pagination="false"
      :loading="loading"
      @change="handleTableChange"
      :bordered="true"
      size="small"
    >
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <template slot="SalePQuantity" slot-scope="text, record">
        <a-input
          size="small"
          class="input"
          type="number"
          v-model="record.SalePQuantity"
          style="text-align: right"
        ></a-input>
      </template>
      <template slot="GiftPName" slot-scope="text, record, index">
        <a-input style="width: 65%" disabled v-model="record.GiftPName"></a-input>&nbsp;
        <a-button @click="addTableReturn(index)" type="primary">
          <a-icon type="search"/>
        </a-button>
      </template>
      <template slot="GiftPQuantity" slot-scope="text, record">
        <a-input
          size="small"
          class="input"
          type="number"
          v-model="record.GiftPQuantity"
          style="text-align: right"
        ></a-input>
      </template>
      <template slot="Remark" slot-scope="text, record">
        <a-input size="small" class="input" v-model="record.Remark"></a-input>
      </template>
      <span slot="action" slot-scope="text, record, index">
        <template>
          <a v-if="hasPerm('GMM_GiftMaterialRuleDetails.Edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider
            v-if="hasPerm('GMM_GiftMaterialRuleDetails.Edit') && hasPerm('GMM_GiftMaterialRuleDetails.Delete')"
            type="vertical"
          />
          <a @click="handleDelete([record.Id], index)">删除</a>
        </template>
      </span>
    </a-table>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button type="primary" @click="addTable">添加</a-button>&nbsp;
      <a-button @click="close">取消</a-button>&nbsp;
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import MaterialChoose from '@/components/MaterialChoose/MaterialChooseCopy1.vue'
import ReturnMaterialChoose from '@/components/ReturnMaterialChoose/MaterialChooseCopy1.vue'
import Myuser from '@/components/MyuserCloose/List.vue'
import moment from 'moment'

export default {
  props: {
    parentObj: Object
  },
  watch: {
    data: {
      handler (n, o) {
        //console.log(n)
        n.forEach(item => {
          if (Number(item.SalePQuantity) < 0) {
            this.$set(item, 'SalePQuantity', 1)
            // this.$message.warning('数量不能小于0')
            return
          }
          if (Number(item.GiftPQuantity) < 0) {
            this.$set(item, 'GiftPQuantity', 1)
            // this.$message.warning('数量不能小于0')
            return
          }
        })
      },
      deep: true,
      immediate: true
    },
    'entity.Object': {
      handler (newVal, oldVal) {
        if (oldVal) {
          //console.log(123, '5555555555')
          this.cc = true
        } else {
          //console.log(123, '00000000000')
          return
        }
        //console.log(newVal, oldVal)
      }
    }
  },
  data () {
    return {
      columns: [
        { title: '销售品名', dataIndex: 'SalePName' },
        { title: '销售品数量', dataIndex: 'SalePQuantity', scopedSlots: { customRender: 'SalePQuantity' } },
        { title: '返料品名', dataIndex: 'GiftPName', scopedSlots: { customRender: 'GiftPName' } },
        { title: '返料品数量', dataIndex: 'GiftPQuantity', scopedSlots: { customRender: 'GiftPQuantity' } },
        { title: '备注', dataIndex: 'Remark', scopedSlots: { customRender: 'Remark' } },

        { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
      ],
      columns2: [
        { title: '销售品名', dataIndex: 'SalePName' },
        { title: '销售品数量', dataIndex: 'SalePQuantity', scopedSlots: { customRender: 'SalePQuantity' } },
        { title: '返料品名', dataIndex: 'GiftPName', scopedSlots: { customRender: 'GiftPName' } },
        { title: '返料品金额', dataIndex: 'GiftPQuantity', scopedSlots: { customRender: 'GiftPQuantity' } },
        { title: '备注', dataIndex: 'Remark', scopedSlots: { customRender: 'Remark' } },

        { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
      ],
      MaterialReturn: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'Id', order: 'desc' },

      data: [],
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      loading: false,
      entity: {},
      rules: {
        RuleName: [{ required: true, message: '未输入', trigger: 'blur' }],
        StartDate: [{ required: true, message: '未输入', trigger: 'change' }],
        EndDate: [{ required: true, message: '未输入', trigger: 'change' }],
        GiftType: [{ required: true, message: '未输入', trigger: 'change' }]
      },
      title: '',
      cc: false,
      Id: '',
      selectedRowKeys: [],
      index: 0
    }
  },
  components: {
    MaterialChoose,
    ReturnMaterialChoose,
    Myuser
  },

  methods: {
    disabledDate (moment) {
      return this.entity.StartDate > moment
    },
    GiftTypeChange (a) {
      console.log(a)
    },
    // 返料类型
    getMaterialReturnType () {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'MaterialReturnType'
        })
        .then(res => {
          this.MaterialReturn = res.Data.DictionaryDetailsList
        })
    },
    // 子表删除
    handleDelete (ids, index) {
      if (ids[0]) {
        var thisObj = this
        this.$confirm({
          title: '确认删除吗?',
          onOk () {
            return new Promise((resolve, reject) => {
              thisObj.$http.post('/GiftManagement/GMM_GiftMaterialRuleDetails/DeleteData', ids).then(resJson => {
                resolve()

                if (resJson.Success) {
                  thisObj.$message.success('操作成功!')

                  thisObj.getDataList()
                } else {
                  thisObj.$message.error(resJson.Msg)
                }
              })
            })
          }
        })
      } else {
        this.data.splice(index, 1)
        //console.log(123)
      }
    },
    // 反填
    getDataList () {
      this.$http
        .post('/GiftManagement/GMM_GiftMaterialRuleMain/GetTheDataOfAll', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Id',
          SortType: 'desc',
          Search: {
            Condition: 'Id',
            Keyword: this.Id
          }
        })
        .then(res => {
          if (res.Success) {
            this.entity = res.Data

            if (this.entity['StartDate']) {
              this.entity['StartDate'] = moment(this.entity['StartDate'])
            }
            if (this.entity['EndDate']) {
              this.entity['EndDate'] = moment(this.entity['EndDate'])
            }
            this.data = res.Data.GGMRD_List

            if (res.Data.Total) {
              const pagination = { ...this.pagination }
              pagination.total = res.Data.Total
              this.pagination = pagination
            }
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    //返料传来的数据
    TableClose (row) {
      //console.log(row)

      this.$set(this.data[this.index], 'GiftPId', row[0].cInvCode)

      this.$set(this.data[this.index], 'GiftPName', row[0].cInvName)

      //console.log(this.data)
    },
    //返料页面
    addTableReturn (index) {
      //console.log(index)
      this.index = index
      this.$refs.ReturnMaterialChoose.openForm(null, this.data)
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      if (this.Id) {
        this.$http
          .post('/GiftManagement/GMM_GiftMaterialRuleMain/GetTheDataOfAll', {
            PageIndex: this.pagination.current,
            PageRows: this.pagination.pageSize,
            SortField: 'Id',
            SortType: 'desc',
            Search: {
              Condition: 'Id',
              Keyword: this.Id
            }
          })
          .then(res => {
            if (res.Success) {
              if (res.Data.Total) {
                const pagination = { ...this.pagination }
                pagination.total = res.Data.Total
                this.pagination = pagination
              }
            } else {
              this.$message.error(res.Msg)
            }
          })
      }
    },

    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    handleChoose (a) {
      //console.log(a)

      //console.log(this.data)
      var ar = []

      this.data.forEach(item => {
        //console.log(this.data)
        a.forEach((val, i) => {
          //console.log(val)
          if (item.ProductId == val.cInvCode) {
            ar.push(val)
            delete a[i]
          }
        })
      })
      //console.log(ar)

      if (ar.length == 0) {
        a.forEach(item => {
          //console.log(this.data)

          this.data.push({
            ProductId: item.Id,
            SalePName: item.cInvName,
            SalePId: item.cInvCode
          })
        })
        //console.log(ar)
        // this.data = [...this.data, ...a]
      } else {
        this.$message.error('重复产品已筛选掉')
        a.forEach(item => {
          //console.log(item)
          this.data = [...this.data, item]
        })

        //console.log(a)
      }
    },
    init () {
      this.visible = true
      this.data = []
      this.entity = {}
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    close () {
      this.visible = false

      this.entity = {}
    },
    openForm (id, title) {
      this.init()
      this.title = title
      this.getMaterialReturnType()
      if (id) {
        // this.loading = true
        this.Id = id
        this.getDataList()
      }
    },

    addTable () {
      //console.log(12113)
      this.$refs.materialChoose.openChoose(null, this.data)
    },
    //保存
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        if (this.data.length == 0) {
          this.$message.warning('请添加产品')
          return
        }
        // this.loading = true
        let num = this.data.some(item => {
          return !item.SalePQuantity || item.SalePQuantity == 0
        })
        let nums = this.data.some(item => {
          return !item.GiftPQuantity || item.GiftPQuantity == 0
        })
        let numsname = this.data.some(item => {
          return !item.GiftPName
        })
        if (num) {
          this.$message.warning('数量不能为空')
          return
        }
        if (nums) {
          this.$message.warning('数量不能为空')
          return
        }
        if (numsname) {
          this.$message.warning('有返料品名为选择，请选择')
          return
        }

        var entityData = this.entity
        var GGMRD_List = [...this.data]
        this.GGMRD_List = GGMRD_List
        //console.log(this.GGMRD_List)
        entityData.GGMRD_List = this.GGMRD_List

        this.$http.post('/GiftManagement/GMM_GiftMaterialRuleMain/SaveData', entityData).then(resJson => {
          this.loading = false

          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false
            this.cc = false
            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    }
  }
}
</script>
